package com.doadway.resource.web.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.doadway.resource.pojo.User;
import com.doadway.resource.service.UserService;


@Controller
public class LoginController {
	@Resource(name="userServiceImpl")
	UserService userService;
	@RequestMapping("/v_login")
	public  String v_login(HttpServletRequest request,HttpServletResponse response)  {
        return "console_login"; 		
	}
	
	@RequestMapping("/login")
	public  String login(HttpServletRequest request,HttpServletResponse response,@Valid @ModelAttribute("user") User user ,BindingResult br,Map<String,Object> model)  {
		System.out.println("前台密码:"+user.getPwd());
		if(br.hasErrors()){
			return "console_login";
		}

		Subject currentUser = SecurityUtils.getSubject();
		//前台传过来时应该用JS加密一次
	//	String  minwen=new Md5Hash( user.getPassword() ).toHex();
		String  psw=user.getPwd();
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),psw);
		//记住我功能不是记住密码而是在整个会话过程记住会话ID,对未登录用户时用购物车有点用
		/*
		if( rememberMe != null ){
			if( rememberMe ){
				token.setRememberMe(true);
			}
		}
		*/
		try {
		  currentUser.login(token);
		} catch (UnknownAccountException uae ) { 
			model.put("info", "用户名不存在");
			return "forward:/v_login";
		} catch (IncorrectCredentialsException ice ) { 
			model.put("info", "密码错误!");
			return "forward:/v_login";
		} catch (LockedAccountException lae ) { 
			model.put("info", "用户已经被锁定不能登录,请与管理员联系");
			return "forward:/v_login";
		} catch (ExcessiveAttemptsException eae ) { 
			model.put("info", "错误次数过多");
			return "forward:/v_login";
		} catch (AuthenticationException ae ) {
			model.put("info", "用户密码错误");
			return "forward:/v_login";
		}
		//验证是否成功登录的方法
		if(currentUser.isAuthenticated()){
			return "index/welcome";
		}
		
        return "index/welcome"; 		
	}
}
